package com.example.demo.controller;

import com.example.demo.model.TestMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.converter.SimpleMessageConverter;
import org.springframework.messaging.handler.annotation.DestinationVariable;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessageSendingOperations;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.messaging.simp.annotation.SendToUser;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

/**
 * 描述：
 * 作者 张超
 * 时间 2018/10/29
 * 项目 springboot-demo v1.0
 * 版本 v1.0
 */
@Controller
public class MessageController {
    @Autowired
    private SimpMessageSendingOperations simpMessageSendingOperations ;
    @Autowired
    private SimpMessagingTemplate simpMessagingTemplate;

    /**
     * 接收客户端发送的消息
     * 访问路径为：setApplicationDestinationPrefixes(配置类里面设置的mywebsocket)+msg
     * @return
     */
    @MessageMapping("/msgto/{userName}")
    @ResponseBody
    public void forwardMsg(@RequestBody TestMsg msg, @DestinationVariable String userName){
        System.err.println("server收到消息"+msg.toString());
        TestMsg msg2 = new TestMsg(1, "这是server发出的消息");
        System.err.println(userName);
        simpMessagingTemplate.convertAndSendToUser(userName,"/queue/test",msg2);
        simpMessagingTemplate.convertAndSend( "/user/zc1/queue/test",msg2);
        return;
    }

    @MessageMapping("/msg2All")
    public void msg2All(@RequestBody TestMsg msg){
        System.err.println("server收到消息"+msg.toString());
        TestMsg msg2 = new TestMsg(1, "这是群发出的消息");
        simpMessagingTemplate.convertAndSend("/topic/msg",msg2);
    }
    @GetMapping("bb")
    public void forwardMsg2(){
        simpMessagingTemplate.convertAndSendToUser("zc1","/queue/test",new TestMsg(1,"这是server发出的消息2"));
        return ;
    }
}
